package deleteface.bank.jqsoft.cn.deleteface;


import android.util.Log;

import okhttp3.*;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 使用okhttp来访问webservice接口
 * @Author: zh
 * @CreateDate: 2018-07-02
 **/
public class OKHttpUtil {

//    private final static Logger log = Logger.getLogger(OKHttpUtil.class);

    public static final MediaType MEDIATYPE_JSON = MediaType.parse("application/json; charset=utf-8");



    protected static OkHttpClient httpClient = new OkHttpClient.Builder()
                                                               .readTimeout(4000, TimeUnit.SECONDS)
                                                               .connectTimeout(1000, TimeUnit.SECONDS)
                                                               .build();

    /**
     * @Description: 远程调用外部的接口(java)
     * @Date: 2018-07-02
     * @Author: zh
     * @param url 接口的路径(http://127.0.0.1:8083/fdss-api/apis/getExecuteProgress)到方法的路径
     * @param jsonStr 入参的参数json格式
     * @return java.lang.String 响应的文本
     */
    public static String postJson(String url,String jsonStr){
        String responseText = "";       //调用接口加密返回的内容
        try {
//            encodedJSONStr = String.valueOf(JsonCipherUtil.encodeJson(jsonStr));
            RequestBody requestBody = RequestBody.create(MEDIATYPE_JSON, jsonStr);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("content-type", "application/json")
                    .build();
            Response response = httpClient.newCall(request).execute();
            if(response.isSuccessful()){
                responseText=response.body().string();
//                decodeResponseStr = String.valueOf(JsonCipherUtil.decodeJson(responseText));
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return responseText;
    }


    public static String post(String url,String param){
        String responseText="";
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("username",param);//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(url)
                .post(formBody.build())//传递请求体
                .build();
        try {
            Response response = client.newCall(request).execute();
            responseText=response.body().string();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseText;
    }


}
/*maven的引用:
 *      <dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
			<version>3.10.0</version>
		</dependency>
 */
